<script setup lang="ts">
import { nextTick, reactive, ref, toRaw } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import { useViewScroll } from "@/hooks/scroll";
import { search_keyword_api, search_api } from "@/api/guider_home";
import { Storage } from "@/utils/database";
import { Router } from "@/utils/router";
import { Toast } from "@/utils/toast";

import PageSticky from "@/components/page/sticky.vue";
import SearchBar from "./components/search-bar.vue";
import SearchTypeItem from "./components/search-type-item.vue";
import ListEmpty from "@/components/list/empty.vue";
import SearchCourseItem from "./components/search-course-item.vue";
import SearchGoodsItem from "./components/search-goods-item.vue";
import SearchArticleItem from "./components/search-article-item.vue";
import SearchNoteItem from "./components/search-note-item.vue";

const historyKey = "search-history";

onLoad(() => {
  historyList.value = Storage.getSync<string[]>(historyKey) || [];
  search_keyword_api().then((resp) => {
    recommendList.value = resp.keyword_arr;
  });
});

const { scrollIndex, scrollToIndex } = useViewScroll();

const queryData = reactive({ keyword: "" });

const searchStatus = ref<"init" | "finish">("init"); // search：搜索中（聚焦）, finish：搜索完成
const searchClick = (type: "search" | "clear") => {
  if (type === "search") {
    const keyword = queryData.keyword.trim();
    if (!keyword) return;
    Toast.showLoading();
    search_api({ keyword })
      .then((resp) => {
        const _typeList: any[] = [];
        // 笔记
        const note = resp.note;
        if (note && note.items.length !== 0) {
          _typeList.unshift({ id: 4, name: `笔记(${note.items.length})` });
        }
        // 文章
        const article = resp.article;
        if (article && article.items.length !== 0) {
          _typeList.unshift({ id: 3, name: `文章(${article.items.length})` });
        }
        // 商品
        const shop = resp.shop;
        if (shop && shop.items.length !== 0) {
          _typeList.unshift({ id: 2, name: `商品(${shop.items.length})` });
        }
        // 课程
        const course = resp.course;
        if (course && course.items.length !== 0) {
          _typeList.unshift({ id: 1, name: `课程(${course.items.length})` });
        }
        // 全部
        if (_typeList.length > 0) {
          _typeList.unshift({ id: 0, name: `全部(${resp.all_count})` });
        }
        typeIndex.value = 0;
        typeList.value = _typeList;
        courseList.value = course.items;
        goodsList.value = shop.items;
        articleList.value = article.items;
        noteList.value = note.items;
        searchStatus.value = "finish";
        Toast.hideLoading();

        nextTick(() => {
          const _historyList = historyList.value;
          const index = _historyList.indexOf(keyword);
          if (index !== -1) _historyList.splice(index, 1);
          _historyList.unshift(keyword);
          historyList.value = _historyList.splice(0, 10);
          Storage.setSync(historyKey, toRaw(historyList.value));
        });
      })
      .catch(() => Toast.hideLoading());
  } else {
    queryData.keyword = "";
    searchStatus.value = "init";
  }
};

const historyList = ref<string[]>([]);
const historyClick = (key: string) => {
  if (key === "del") {
    historyList.value = [];
    Storage.deleteSync(historyKey);
  } else {
    recommendClick(key);
  }
};
const recommendList = ref<string[]>([]);
const recommendClick = (key: string) => {
  queryData.keyword = key;
  searchClick("search");
};

const typeIndex = ref(0);
const typeList = ref<any[]>([]);
const typeClick = (index: number) => {
  typeIndex.value = index;
  scrollToIndex(index);
};

const courseList = ref<any[]>([]);
const courseClick = (index: number) => {
  const course = courseList.value[index];
  course.search_type === 2
    ? Router.navigateTo(`/package/study/pages/course/detail?id=${course.id}`)
    : Router.navigateTo(`/package/mall/pages/train/detail?id=${course.id}`);
};

const goodsList = ref<any[]>([]);
const goodsClick = (id: string) => {
  Router.navigateTo(`/package/mall/pages/goods/detail?id=${id}`);
};

const articleList = ref<any[]>([]);
const articleClick = (id: string) => {
  Router.navigateTo(`/package/famous-talk/pages/detail/index?id=${id}`);
};

const noteList = ref<any[]>([]);
const noteClick = (index: number) => {
  const note = noteList.value[index];
  note.search_type === 5
    ? Router.navigateTo(
        note.type === 2
          ? `/package/novice/pages/note/detail2?id=${note.id}`
          : `/package/novice/pages/note/detail?id=${note.id}`
      )
    : Router.navigateTo(
        note.type === 2
          ? `/package/guider/pages/note/detail2?id=${note.id}`
          : `/package/guider/pages/note/detail?id=${note.id}`
      );
};
</script>

<template>
  <PageSticky>
    <SearchBar v-model="queryData.keyword" @search="searchClick" />

    <scroll-view
      class="search-type"
      v-if="searchStatus === 'finish' && typeList.length > 0"
      scroll-x
      enhanced
      :show-scrollbar="false"
    >
      <view class="search-type-space"></view>
      <view
        class="search-type-item"
        v-for="i of typeList"
        :key="i.id"
        @click="typeClick(i.id)"
      >
        <SearchTypeItem :isActive="typeIndex === i.id" :text="i.name" />
      </view>
    </scroll-view>
  </PageSticky>

  <view class="search-init" v-if="searchStatus === 'init'">
    <template v-if="historyList.length !== 0">
      <view class="search-init-title">搜索历史</view>
      <image
        class="search-init-del"
        src="/static/search-del.png"
        @click="historyClick('del')"
      />
      <view class="search-init-wrapper">
        <view
          class="search-init-keyword"
          v-for="i of historyList"
          :key="i"
          @click="historyClick(i)"
        >
          {{ i }}
        </view>
      </view>
    </template>

    <template v-if="recommendList.length !== 0">
      <view class="search-init-title">推荐搜索</view>
      <view class="search-init-wrapper">
        <view
          class="search-init-keyword"
          v-for="i of recommendList"
          :key="i"
          @click="recommendClick(i)"
        >
          {{ i }}
        </view>
      </view>
    </template>
  </view>

  <scroll-view
    class="search-data"
    v-else
    scroll-y
    :scroll-into-view="`data-${scrollIndex}`"
  >
    <ListEmpty
      v-if="typeList.length === 0"
      text="没有找到合适结果，试试搜搜其他的吧~"
    />

    <template v-else>
      <view class="search-data-space" id="data-0"></view>
      <template v-if="courseList.length > 0">
        <view class="search-data-title" id="data-1">课程</view>
        <view class="search-data-wrapper">
          <view
            class="search-data-item"
            v-for="(i, d) of courseList"
            :key="i.id"
            @click="courseClick(d)"
          >
            <view class="search-data-line" v-if="d > 0"></view>
            <SearchCourseItem :info="i" />
          </view>
        </view>
      </template>

      <template v-if="goodsList.length > 0">
        <view class="search-data-title" id="data-2">商品</view>
        <view class="search-data-wrapper">
          <view
            class="search-data-item"
            v-for="(i, d) of goodsList"
            :key="i.id"
            @click="goodsClick(i.id)"
          >
            <view class="search-data-line" v-if="d > 0"></view>
            <SearchGoodsItem :info="i" />
          </view>
        </view>
      </template>

      <template v-if="articleList.length > 0">
        <view class="search-data-title" id="data-3">文章</view>
        <view class="search-data-wrapper">
          <view
            class="search-data-item"
            v-for="(i, d) of articleList"
            :key="i.id"
            @click="articleClick(i.id)"
          >
            <view class="search-data-line" v-if="d > 0"></view>
            <SearchArticleItem :info="i" />
          </view>
        </view>
      </template>

      <template v-if="noteList.length > 0">
        <view class="search-data-title" id="data-4">笔记</view>
        <view class="search-data-wrapper">
          <view
            class="search-data-item"
            v-for="(i, d) of noteList"
            :key="i.id"
            @click="noteClick(d)"
          >
            <view class="search-data-line" v-if="d > 0"></view>
            <SearchNoteItem :info="i" />
          </view>
        </view>
      </template>

      <view class="search-data-safe"></view>
    </template>
  </scroll-view>
</template>

<style lang="scss">
page {
  padding-bottom: 0;
  background-color: #ffffff;
}

.search-type {
  height: 88rpx;
  white-space: nowrap;

  .search-type-space,
  .search-type-item {
    display: inline-block;
    vertical-align: top;
  }

  .search-type-space {
    width: 30rpx;
  }

  .search-type-item {
    padding: 0 10rpx;
    margin-top: 16rpx;
    margin-right: 40rpx;
  }
}

.search-init {
  position: relative;
  padding-top: 28rpx;

  .search-init-title {
    padding-left: 30rpx;
    margin-bottom: 20rpx;
    font-size: 30rpx;
    color: #2d2d2d;
    line-height: 40rpx;
    font-weight: bold;
  }

  .search-init-del {
    position: absolute;
    top: 34rpx;
    right: 30rpx;
    width: 24rpx;
    height: 28rpx;
  }

  .search-init-wrapper {
    display: flex;
    align-items: flex-start;
    flex-wrap: wrap;
    padding-left: 30rpx;
    padding-bottom: 24rpx;
  }

  .search-init-keyword {
    padding: 0 26rpx;
    margin-right: 24rpx;
    margin-bottom: 24rpx;
    font-size: 28rpx;
    color: #999999;
    line-height: 60rpx;
    border-radius: 36rpx;
    background-color: #f6f6f6;
  }
}

.search-data {
  height: calc(100vh - 188rpx);

  .search-data-space {
    height: 40rpx;
  }

  .search-data-title {
    padding-left: 30rpx;
    margin-bottom: 10rpx;
    font-size: 30rpx;
    color: #333333;
    line-height: 42rpx;
    font-weight: bold;
  }

  .search-data-wrapper {
    margin-bottom: 30rpx;
  }

  .search-data-item {
    position: relative;
    padding: 20rpx 30rpx;
  }

  .search-data-line {
    position: absolute;
    left: 30rpx;
    top: 0;
    right: 30rpx;
    border-bottom: 2rpx solid #e6e6e6;
  }

  .search-data-safe {
    height: 50rpx;
    padding-bottom: env(safe-area-inset-bottom);
  }
}
</style>